package com.martin.lib_base.net.adapter

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import com.martin.lib_base.ktx.noNull

class DoubleTypeAdapter : TypeAdapter<Double>() {

    override fun write(out: JsonWriter, value: Double?) {
        if (value == null) {
            out.nullValue()
        } else {
            out.value(value)
        }
    }

    override fun read(reader: JsonReader): Double {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull()
            return 0.0
        }
        return try {
            reader.nextDouble()
        } catch (e: Exception) {
            0.0
        }
    }
}